package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class My_Profile_Sell extends ListActivity {
	// List is a linked list
	// Map is a hash table: String -> Object
	private List<Map<String, Object>> mData;
	final Bundle extras = new Bundle();
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	MyAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_profile_sell_main);
		String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Sell.this);
		String username = usernamePassword[0];
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		
		showDialog(SPINNER);
		progThread = new ProgressThread(mhandler,params, 0, 0);
		progThread.start();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			int from = msg.getData().getInt("from");
			if(from == 0){
				if(returnedData.contains("error")){
					Toast.makeText(My_Profile_Sell.this, "Network Error", Toast.LENGTH_SHORT).show();
				}
				else{
					mData = getData(returnedData);
				
					adapter = new MyAdapter(My_Profile_Sell.this);
					setListAdapter(adapter);
				}
			}
			else if(from == 1 || from == 2){
				int position = msg.getData().getInt("position");
				if(returnedData.contains("delete_successful")){
					mData.remove(position);
					adapter.notifyDataSetChanged();
					Toast.makeText(My_Profile_Sell.this,"Deletion is successful", Toast.LENGTH_SHORT).show();
				}
				else if(returnedData.contains("delete_failed"))
					Toast.makeText(My_Profile_Sell.this,"Deletion failed", Toast.LENGTH_SHORT).show();
				else if(returnedData.contains("insufficient_credit"))
					Toast.makeText(My_Profile_Sell.this,"You have used up all your credits. Making this change would make your credit negative.", Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(My_Profile_Sell.this,"Network Error", Toast.LENGTH_SHORT).show();
		}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		List<NameValuePair> params;
		int from;
		int position;

		ProgressThread(Handler h,List<NameValuePair> p, int f, int pos) {
			mHandler = h;
			params = p;
			from = f;
			position = pos;
		}

		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			String returnedData;
			if(from == 0){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_lend_history_display.jsp");
				
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 1){
				returnedData = NetworkUtility.sendHTTP(params, "http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_remove.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("position", position);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}else if(from == 2){
				returnedData = NetworkUtility.sendHTTP(params, "http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/lend_remove.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("position", position);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
		
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}

	private List<Map<String, Object>> getData(String data) {
		List< Map<String, Object> > list = new ArrayList< Map<String, Object> >();
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		try{
		    JSONArray jArray = new JSONArray(data);
		    JSONObject json_data=null;
		    int length = jArray.length();
		    for(int i = 0; i < length; i++){
		    json_data = jArray.getJSONObject(i);
		    map = new HashMap<String, Object>();
			map.put("title", json_data.getString("Title"));
			map.put("edition", json_data.getString("Edition"));
			map.put("courses", json_data.getString("Courses"));
			map.put("authors", json_data.getString("Authors"));
			map.put("publishers", json_data.getString("Publisher"));
			map.put("ISBN", json_data.getString("ISBN"));
			map.put("date", json_data.getString("Date"));
			map.put("status", json_data.getString("Status"));
			map.put("ID", json_data.getString("CopyID"));
			map.put("Condition", json_data.getString("Condition"));
			map.put("Price", json_data.getString("Price"));
			list.add(map);
		    }
		}catch (JSONException e) {
            throw new RuntimeException(e);
        }

		return list;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		// Log.v("MyListView4-click", (String)mData.get(position).get("title"));
//		Intent myIntent = new Intent(this,
//				ViewBookDetailsTab.class);
//		myIntent.putExtra("title", (String) mData.get(position).get("title"));
//		myIntent.putExtra("edition", (String) mData.get(position)
//				.get("edition"));
//		myIntent.putExtra("course", (String) mData.get(position)
//				.get("course"));
//		myIntent.putExtra("authors", (String) mData.get(position)
//				.get("authors"));
//		myIntent.putExtra("publishers",
//				(String) mData.get(position).get("publishers"));
//		myIntent.putExtra("ISBN", (String) mData.get(position).get("ISBN"));
//		startActivity(myIntent);
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ViewHolder holder = null;
		private final int TYPE_TOSELL = 0;
		private final int TYPE_SOLD = 1;
		private final int TYPE_ERROR = -1;
		
		private final int VIEW_NUM = 2;

		
		
		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}


		public int getCount() {
			return mData.size();
		}


		public Object getItem(int arg0) {
			return null;
		}


		public long getItemId(int arg0) {
			return 0;
		}
		

		@Override
		public int getItemViewType(int position) {
			String status = (String) mData.get(position).get("status");
			if ( status.contains("Listed") || status.contains("In Stock"))
				return TYPE_TOSELL;
			else if ( status.equals("Sold") || status.contains("User Side"))
				return TYPE_SOLD;
			else 
				return TYPE_ERROR;
		}

		@Override
		public int getViewTypeCount() {
			return VIEW_NUM;
		}




		public final class ViewHolder {
			public TextView title;
			public TextView edition;
			public TextView course;
			public TextView authors;
			public TextView publishers;
			public TextView ISBN;
			public TextView listOrSold;
			public Button[] button;
		}


		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.my_profile_sell, null);
				holder.title = (TextView) convertView.findViewById(R.id.tv_MyProfileSell_title);
				holder.edition = (TextView) convertView
						.findViewById(R.id.tv_MyProfileSell_edition);
				holder.course = (TextView) convertView
						.findViewById(R.id.tv_MyProfileSell_course);
				holder.authors = (TextView) convertView
						.findViewById(R.id.tv_MyProfileSell_authors);
				holder.publishers = (TextView) convertView
						.findViewById(R.id.tv_MyProfileSell_publishers);
				holder.ISBN = (TextView) convertView.findViewById(R.id.tv_MyProfileSell_ISBN);
				holder.listOrSold = (TextView) convertView.findViewById(R.id.tv_MyProfileSell_listOrSold);
				holder.button = new Button[2];
				holder.button[0] = (Button) convertView.findViewById(R.id.b_MyProfileSell_Modify);
				holder.button[1] = (Button) convertView.findViewById(R.id.b_MyProfileSell_RemoveOrRelist);
				
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.title.setText((String) mData.get(position).get("title"));
			holder.edition.setText("Edition: "+ (String) mData.get(position).get("edition"));
			if((String) mData.get(position).get("course") == null)
				holder.course.setText("Courses: N/A");
			else
				holder.course.setText("Courses: "+ (String) mData.get(position).get("course"));
			if((String) mData.get(position).get("authors") == null)
				holder.authors.setText("Authors: N/A");
			else
				holder.authors.setText("Authors: "+(String) mData.get(position).get("authors"));
			if((String) mData.get(position).get("publishers") == null)
				holder.publishers.setText("Publishers: N/A");
			else
				holder.publishers.setText("Publishers: "+(String) mData.get(position).get(
					"publishers"));
			holder.ISBN.setText("ISBN: " + (String) mData.get(position).get("ISBN"));
					
			int type = getItemViewType(position);
			final String status = (String) mData.get(position).get("status");
			switch(type){
			case TYPE_TOSELL:
				if(status.contains("Listed"))
					holder.listOrSold.setText("Waiting for buyer. Listed on " + (String) mData.get(position).get("date"));
				else if(status.contains("In Stock"))
					holder.listOrSold.setText("Waiting for borrower. Listed on " + (String) mData.get(position).get("date"));
				holder.button[0].setVisibility(View.VISIBLE);
				holder.button[1].setText("Remove");
				holder.button[0].setTag(position);
				holder.button[0].setOnClickListener(new View.OnClickListener() {
					

					public void onClick(View v) {
						int position = Integer.parseInt(v.getTag().toString());
						Intent myIntent = new Intent(My_Profile_Sell.this,
								SellLend_Confirm.class);
						//TODO
						myIntent.putExtra("modify", true);
						myIntent.putExtra("condition", (String) mData.get(position).get("Condition"));
						
						// Discards decimal places using String.split
						String priceStr = (String) mData.get(position).get("Price");
						String[] tokens = priceStr.split("\\.");   // required for special character "."
						myIntent.putExtra("price", tokens[0]);
						
						myIntent.putExtra("copyid", (String) mData.get(position).get("ID"));
						myIntent.putExtra("title", (String) mData.get(position).get("title"));
						myIntent.putExtra("authors", (String) mData.get(position).get("authors"));
						myIntent.putExtra("ISBN", (String) mData.get(position).get("ISBN"));
						myIntent.putExtra("publishers", (String) mData.get(position).get("publishers"));
						myIntent.putExtra("edition", (String) mData.get(position).get("edition"));
						myIntent.putExtra("courses", (String) mData.get(position).get("course"));
						if(status.contains("Listed")){
							myIntent.putExtra("type","sell");
						}
						else if(status.contains("In Stock")){
							myIntent.putExtra("type","lend");
						}
						startActivity(myIntent);
						
					}
				});
				
				holder.button[1].setTag(position);
				holder.button[1].setOnClickListener(new View.OnClickListener() {
					

					public void onClick(final View v) {
				    	AlertDialog.Builder builder = new AlertDialog.Builder(My_Profile_Sell.this);
				    	builder.setMessage("Are you sure you don't want to sell/lend this book anymore?")
				    	       .setCancelable(false)
				    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				    	           public void onClick(DialogInterface dialog, int id) {
										int position = Integer.parseInt(v.getTag().toString());
										
										String copyid = (String) mData.get(position).get("ID");
										String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Sell.this);
										String username = usernamePassword[0];
										String status = (String) mData.get(position).get("status");
										List<NameValuePair> params = new ArrayList<NameValuePair>(2);
										params.add(new BasicNameValuePair("username", username));
										params.add(new BasicNameValuePair("copyid", copyid));
										if(status.contains("Listed")){
											//returnResult = NetworkUtility.sendHTTP(params, "http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_remove.jsp");
											showDialog(SPINNER);
											progThread = new ProgressThread(mhandler, params, 1, position);
											progThread.start();
										}
										else{
											//returnResult = NetworkUtility.sendHTTP(params, "http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/lend_remove.jsp");
											showDialog(SPINNER);
											progThread = new ProgressThread(mhandler, params, 2, position);
											progThread.start();
										}
										
				    	           }
				    	       })
				    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				    	           public void onClick(DialogInterface dialog, int id) {
				    	                dialog.cancel();
				    	           }
				    	       });
				    	AlertDialog alert = builder.create();
				    	alert.show();
						
					}
				});
						
				break;
			case TYPE_SOLD:
				holder.button[0].setVisibility(View.GONE);
				if(status.contains("User Side")){
					holder.button[1].setVisibility(View.GONE);
					holder.listOrSold.setText("Lent to borrower on " + (String) mData.get(position).get("date"));
				}
				else{
					holder.listOrSold.setText("Sold on " + (String) mData.get(position).get("date"));
					holder.button[1].setVisibility(View.GONE);
//					holder.button[1].setText("Sell/Lend this Copy");
//					holder.button[1].setTag(position);
//					holder.button[1].setOnClickListener(new View.OnClickListener() {
//	
//						public void onClick(View v) {
//							int position = Integer.parseInt(v.getTag().toString());
//							Intent myIntent = new Intent(My_Profile_Sell.this,
//									SellLend_Confirm.class);
//							myIntent.putExtra("modify", true);
//							//TODO
//							myIntent.putExtra("type","sell-resell");
//							myIntent.putExtra("condition", (String) mData.get(position).get("Condition"));
//							myIntent.putExtra("price", (String) mData.get(position).get("Price"));
//							myIntent.putExtra("copyid", (String) mData.get(position).get("ID"));
//							
//							myIntent.putExtra("title", (String) mData.get(position).get("title"));
//							myIntent.putExtra("authors", (String) mData.get(position).get("authors"));
//							myIntent.putExtra("ISBN", (String) mData.get(position).get("ISBN"));
//							myIntent.putExtra("publishers", (String) mData.get(position).get("publishers"));
//							myIntent.putExtra("edition", (String) mData.get(position).get("edition"));
//							myIntent.putExtra("courses", (String) mData.get(position).get("course"));
//							startActivity(myIntent);
//						}
//					});
				}
				break;
			case TYPE_ERROR:
			}
				
			return convertView;
		}

	}
}
